#include "stm32f2xx.h"
#include "object_dict.h"
#include "can_transmit_queue.h"
#include "can_od_server.h"

#define CLIENT_PUSH 0x01 
#define CLIENT_PULL 0x02 
#define CLIENT_CALL 0x04
#define SERVER_PUSH_ACK 0x08 
#define SERVER_PULL_BACK 0x10 
#define SERVER_CALL_ACK 0x20 

struct can_transmit_queue server_transmit_queue;
extern struct object_dict OD;

static void data2frame(const int data, uint8_t frame[4])
{
	frame[0]=  data& 0xFF;
	frame[1]= (data& 0xFF00)>>8;
	frame[2]= (data& 0xFF0000)>>16;
	frame[3]= (data& 0xFF000000)>>24; 
}

int server_push(struct object_dict* od, int index ,void* data_address)
{
    enum entry_type type = ENTRY_IDEL;
	CanTxMsg TxMessage;
	TxMessage.StdId = od->can_id;
	TxMessage.ExtId = 0x01;
	TxMessage.RTR = CAN_RTR_DATA;
	TxMessage.IDE = CAN_ID_STD;
	TxMessage.DLC = 2;
	TxMessage.Data[0]= SERVER_PUSH_ACK ;            
	TxMessage.Data[1]= index;                
	type = get_entry_type(&OD, index);
	set_dict_entry(&OD, index, data_address, type);
	insert_queue(&server_transmit_queue, &TxMessage);
    return 1;
}

int server_pull_back(const struct object_dict* od, int index)
{
    int data = 0;
    enum entry_type type = ENTRY_IDEL;
	CanTxMsg TxMessage;
	TxMessage.StdId = od->can_id;
	TxMessage.ExtId = 0x01;
	TxMessage.RTR = CAN_RTR_DATA;
	TxMessage.IDE = CAN_ID_STD;
	TxMessage.DLC = 6;
	TxMessage.Data[0]= SERVER_PULL_BACK ;      
	TxMessage.Data[1]= index;                    
	type = get_entry_type(&OD, index);
	get_dict_entry(&OD, index, (void*)&data, type);
    data2frame(data, TxMessage.Data + 2);
	insert_queue(&server_transmit_queue, &TxMessage);
    return 1;
    
}

int server_call(const struct object_dict* od, int index)
{
	CanTxMsg TxMessage;
	TxMessage.StdId = od->can_id;
	TxMessage.ExtId = 0x01;
	TxMessage.RTR = CAN_RTR_DATA;
	TxMessage.IDE = CAN_ID_STD;
	TxMessage.DLC = 2;
	TxMessage.Data[0] = SERVER_CALL_ACK ;            
	TxMessage.Data[1] = index;                
	insert_queue(&server_transmit_queue, &TxMessage);
	call_dict_entry(&OD, index);
    return 1;
}
